package com.ujiuye.web;

import com.ujiuye.entity.Student;
import com.ujiuye.service.StudentService;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;
import java.util.UUID;

@MultipartConfig
@WebServlet("/addStu")
public class AddStuServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 解决中文乱码
//        req.setCharacterEncoding("utf-8");
//        resp.setContentType("test/html;charset=utf-8");
        PrintWriter pw = resp.getWriter();
        // 获取上传的图片名
        Part part = req.getPart("spic");
        String fileName = part.getSubmittedFileName();
        // 重命名图片名
        fileName= UUID.randomUUID()+fileName;
        // 设置上传路径
        String path = "F:/pic";
        // 获取表单数据   存到map中
        Map<String,String[]> map = req.getParameterMap();
        Student s = new Student();
        // 调用BeanUtils中的映射方法将map中的数据映射到对象中
        try {
            BeanUtils.populate(s,map);
            // 调用service中的添加方法
            StudentService ss = new StudentService();
            // 在添加之前给spic属性赋值
            s.setSpic(fileName);
            boolean b = ss.addStu(s);
            if (b){
                //添加成功-->显示学生信息
                // 上传图片
                File f = new File(path);
                // 如果路径不存在则创建
                if (!f.exists()){
                    f.mkdir();
                }
                // 上传
                part.write(path+File.separator+fileName);
                resp.sendRedirect("queryStuByPage");
            }else{
                pw.println("添加失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
